<template>
	<view>
		<!-- #ifdef MP-WEIXIN -->
		<view>
			<view class='header'>
				<image src='../../static/wx_login.png'></image>
			</view>
			<view class='content'>
				<view>申请获取以下权限</view>
				<text>获得你的公开信息(昵称，头像、地区等)</text>
			</view>
			<button class='bottom' type='primary' open-type="getUserInfo" @getuserinfo="wxGetUserInfo">
				授权登录
			</button>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		login,
		putUserInfo,
		putPhone
	} from '../../models/login.js'
	export default {
		data() {
			return {}
		},
		onLoad() {

		},
		methods: {
			// 登录并获取用户信息
			wxGetUserInfo() {
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						var code = loginRes.code
						uni.getUserInfo({
							provider: 'weixin',
							success: function(infoRes) {
								var userInfo = {
									avatarUrl: infoRes.userInfo.avatarUrl,
									nickName: infoRes.userInfo.nickName,
									gender: infoRes.userInfo.gender,
									province: infoRes.userInfo.province,
									city: infoRes.userInfo.city,
									country: infoRes.userInfo.country,
								}
								var phoneInfo = {
									encryptedData: infoRes.encryptedData,
									iv: infoRes.iv,
								}
								login(code).then((res) => {
									uni.setStorageSync('token', res.data.token);
									var hasMobile = res.data.hasMobile
									var hasUserInfo = res.data.hasUserInfo

									if (hasMobile == false) { //是否需要用户授权拉手机号码
										// console.log(phoneInfo)
										putPhone(phoneInfo).then((res) => {})
									}
									if (hasUserInfo == false) { //是否已经从微信拉取过用户信息了
										// console.log(userInfo)
										putUserInfo(userInfo).then((res) => {})
									}
									// console.log(res)
									uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
										delta: 1
									})
								}).catch(err => {
									// console.log(err)
								})
							}
						})
					}
				})
			}
		}
	}
</script>

<style>
	.header {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;
	}

	.header image {
		width: 200rpx;
		height: 200rpx;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 70rpx 50rpx;
		font-size: 35rpx;
	}
</style>
